import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
    // const count = ref(0)
    // const doubleCount = computed(() => count.value * 2)
    // function increment() {
    //     count.value++
    // }

    // return { count, doubleCount, increment }

    // 购物车列表
    const cartList = ref([])
    // 我的订单列表
    const myorderList = ref([]) // id, title,price, orderList,status
    // 购物车商品总数量
    const totalCount = computed(() => {
        let res = 0
        cartList.value.forEach(item => {
            res += item.count
        })
        return res
    })
    // 购物车选中商品总价格
    const totalPrice = computed(() => {
        let res = 0
        cartList.value.forEach(item => {
            if (item.checked == true) {
                res += item.count * item.price
            }
        })
        return res.toFixed(2)
    })
    // 计算确认订单列表
    const orderList = computed(() => {
        return cartList.value.filter(item => item.checked == true)
    })


    // 将商品加入到购物车
    const addItem = (payload) => { // 详情页商品对象
        const index = cartList.value.findIndex(item => item.id == payload.id) // 遍历购物车数组， 找到id对应的商品的索引
        if (index > -1) {
            cartList.value[index].count++
        } else {
            cartList.value.push({
                ...payload, // 展开商品对象
                count: 1, // 商品数量
                checked: false // 是否选中
            })
        }
    }
    // 删除购物车中商品
    const deleteItem = (id) => {
        cartList.value = cartList.value.filter(item => item.id != id)
    }

    // 将订单加入到我的订单列表中
    const addmyOrder = (payload) => {
        myorderList.value.push(payload)
    }

    // 修改订单状态为已付款/待发货
    const updateOrderStatus = (id) => { // id：订单id
        myorderList.value.find(item => item.id == id).status = 2
    }

    return { cartList, myorderList, totalCount, totalPrice, orderList, addItem, deleteItem, addmyOrder, updateOrderStatus }
}, {
    persist: true,
})